package com.yu.config.mybatisHandler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yu.common.constant.Constant;
import com.yu.config.base.BasePO;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    private final static Logger logger = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BasePO) {
                BasePO basePO = (BasePO) metaObject.getOriginalObject();
                setBasePO(basePO, true);
            }


        } catch (Exception e) {
            throw new RuntimeException("自动注入异常 => " + e.getMessage());
        }
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BasePO) {
            BasePO basePO = (BasePO) metaObject.getOriginalObject();
            setBasePO(basePO, false);
        }

    }

    private void setBasePO(BasePO basePO, boolean isInsert) {
        String userId = Constant.USER_ID_DEFAULT;
        String deptId = Constant.DEPT_ID_DEFAULT;

//        Map map = loginController.readToken();
//        if (map.get("deptId") != null && (map.get("userId") != null)) {
//            userId = String.valueOf(map.get("userId"));
//            deptId = String.valueOf(map.get("deptId"));
//        }
        if (isInsert) {
            Date currentTime = ObjectUtil.isNotNull(basePO.getCreateTime()) ? basePO.getCreateTime() : new Date();
            basePO.setCreateTime(currentTime);
            basePO.setUpdateTime(currentTime);

            if (StringUtils.isBlank(basePO.getCreateBy())) {
                basePO.setCreateBy(userId);
                basePO.setUpdateBy(userId);
            }
            if (StringUtils.isBlank(basePO.getDeptId())) {
                basePO.setDeptId(deptId);
            }
        } else {
            Date updateTime = ObjectUtil.isNotNull(basePO.getUpdateTime()) ? basePO.getUpdateTime() : new Date();
            if (StringUtils.isBlank(basePO.getCreateBy())) {
                basePO.setUpdateBy(userId);
            }
            if (StringUtils.isBlank(basePO.getDeptId())) {
                basePO.setDeptId(deptId);
            }
            basePO.setUpdateTime(updateTime);
        }

        boolean isDelete = basePO.getIsDelete() == null ? false : basePO.getIsDelete();
        basePO.setIsDelete(isDelete);
    }
}
